package com.franklin.icharm;

import com.franklin.icharm.service.MainService;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class PairingActivity extends Activity {

	protected static final String TAG = "PairingActivity";
	private TextView tvCountDown ;
	private CountDownTimer pTimer ; 
	private Context mContext;
	public static String mDeviceAddr = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pairing);
		tvCountDown = (TextView)findViewById(R.id.tvTimer);
		startTimer();
		serReceiverInit();
		 startScanning(true);
		 mContext = this;

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (pTimer != null)
			pTimer.cancel();
		unregisterReceiver(appReceiver);
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.pairing, menu);
		return true;
	}
	
	private void startTimer()
	{
		pTimer = new CountDownTimer(30*1000, 1000){

			@Override
			public void onFinish() {
				tvCountDown.setText("0");
				new AlertDialog.Builder(PairingActivity.this)
			    .setTitle(R.string.pairing_error_title)
			    .setMessage(R.string.pairing_error_msg)
			    .setNegativeButton(R.string.button_retry, new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int which) { 
			    		startTimer();
			        }
			     })
			    .setIcon(R.drawable.ic_launcher)
			     .show();
			}

			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub
				tvCountDown.setText(String.format("%d", millisUntilFinished /1000 ));

			}
			
		}.start();
	}

	private void startScanning(boolean bEnable)
	{
		Intent intent = new Intent();
		intent.setAction(MainService.ACTION_APP_BLE_SCANNING);
		intent.putExtra(MainService.EXTRA_ENABLE, bEnable);
		sendBroadcast(intent);
	}
	
	private void startConnect(String sAddress)
	{
		Intent intent = new Intent();
		intent.setAction(MainService.ACTION_APP_GO_CONNECTION);
		if (sAddress != null)
			intent.putExtra(MainService.EXTRA_DEVICE_ADDRESS, sAddress);
		sendBroadcast(intent);
	}
	
	private IntentFilter appFilter;

	private void serReceiverInit()
	{
		// Register the BroadcastReceiver
		appFilter = new IntentFilter(MainService.ACTION_SCANNED_DEVICE);
		appFilter.addAction(MainService.ACTION_CONNECTED_DEVICE);
		registerReceiver(appReceiver, appFilter);
	}
	private BroadcastReceiver appReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (MainService.ACTION_SCANNED_DEVICE.equals(action))
			{

				String dname = intent.getExtras().getString(MainService.EXTRA_DEVICE_NAME);
				String daddress = intent.getExtras().getString(MainService.EXTRA_DEVICE_ADDRESS);
				int rssi = intent.getExtras().getInt(MainService.EXTRA_DEVICE_RSSI);
				Log.d(TAG, String.format("%s %s %d", dname, daddress, rssi));
				if (dname.contains("arm"))
				{
					Log.d(TAG, String.format("@_@_@_@ found"));
					mDeviceAddr = daddress;
					startScanning(false);
					UserConfig uc = new UserConfig(mContext);
					uc.setConf(UserConfig.KV_DEVICE_BINDING_ADDRESS, daddress);
					pTimer.cancel();
					startConnect(daddress);
					
				}
			}else if (MainService.ACTION_CONNECTED_DEVICE.equals(action))
			{
				new AlertDialog.Builder(PairingActivity.this)
			    .setTitle(R.string.pairing_success_title)
			    .setMessage(R.string.pairing_success_msg)
			    .setNegativeButton(R.string.button_done, new DialogInterface.OnClickListener() {
			        public void onClick(DialogInterface dialog, int which) { 
			        	Intent resultData = new Intent();
			        //	resultData.putExtra("valueName", "valueData");
			        	PairingActivity.this.setResult(Activity.RESULT_OK, resultData);
			        	finish();
			        }
			     })
			    .setIcon(R.drawable.ic_launcher)
			    .show();
			}
		}
	};

}
